/**
 * 权限验证工具函数
 */
import { getToken, getUserInfo } from './storage';

/**
 * 检查是否已登录
 * @returns {Boolean} 是否已登录
 */
export const isLoggedIn = () => {
  const token = getToken();
  return !!token;
};

/**
 * 权限验证
 * @param {Object} options 配置项
 * @returns {Promise} Promise对象
 */
export const checkAuth = (options = {}) => {
  const { redirect = true, showToast = true } = options;
  
  return new Promise((resolve, reject) => {
    if (isLoggedIn()) {
      resolve(true);
    } else {
      if (showToast) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
      }
      
      if (redirect) {
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/index/log/login'
          });
        }, 1500);
      }
      
      reject(new Error('未登录'));
    }
  });
};

/**
 * 跳转前检查登录状态
 * @param {Object} options 配置项
 */
export const navigateWithAuth = (options) => {
  const { url, redirect = true, showToast = true } = options;
  
  checkAuth({ redirect, showToast })
    .then(() => {
      uni.navigateTo({ url });
    })
    .catch(() => {
      // 已在checkAuth中处理
    });
};

/**
 * 获取用户角色
 * @returns {String} 用户角色
 */
export const getUserRole = () => {
  const userInfo = getUserInfo();
  return userInfo ? userInfo.role || 'user' : 'guest';
};

/**
 * 检查是否有权限
 * @param {String|Array} requiredRoles 需要的角色
 * @returns {Boolean} 是否有权限
 */
export const hasPermission = (requiredRoles) => {
  const userRole = getUserRole();
  
  if (userRole === 'admin') {
    return true;
  }
  
  if (Array.isArray(requiredRoles)) {
    return requiredRoles.includes(userRole);
  }
  
  return requiredRoles === userRole;
}; 